package wei.xinya.springTransaction.service.impl;

import org.springframework.stereotype.Service;
import wei.xinya.springTransaction.dao.GoodsDao;
import wei.xinya.springTransaction.dao.SaleDao;
import wei.xinya.springTransaction.entity.Goods;
import wei.xinya.springTransaction.entity.Sale;
import wei.xinya.springTransaction.exception.NotEnoughException;
import wei.xinya.springTransaction.service.SaleService;

import javax.annotation.Resource;

@Service
public class SaleServiceImpl implements SaleService {

    @Resource
    private SaleDao saleDao;
    @Resource
    private GoodsDao goodsDao;

    @Override
    public void buy(Integer goodsId, Integer num) {
        System.out.println("购买方法的开始");

        // 生成销售记录
        saleDao.insertSale(new Sale(goodsId, num));

        // 查询商品
        Goods goods = goodsDao.selectById(goodsId);
        if (goods == null) {
            throw new NotEnoughException("商品已售罄！");
        } else if (goods.getAmount() < num) {
            throw new NotEnoughException("商品库存不足！");
        }

        // 更新商品库存
        goodsDao.updateGoods(new Goods(goodsId, num));

        System.out.println("购买方法的结束");
    }
}
